package com.cloud.sys.controller;

import com.cloud.sys.common.ResponseWrapper;
import com.cloud.sys.config.YmlConfig;
import com.cloud.sys.entity.SysUser;
import com.cloud.sys.service.SysUserService;
import com.cloud.sys.utils.RedisUtils;
import com.cloud.sys.vo.PageUtil;
import com.cloud.sys.vo.SysUserVo;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.RequestWrapper;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * (SysUser)表控制层
 *
 * @author makejava
 * @since 2018-11-04 11:09:36
 */
@RestController
@RequestMapping(value = "/sysUser")
@Slf4j
@Api(value = "用户管理", tags = "用户管理--查询 修改 新增")
public class SysUserController {
    /**
     * 服务对象
     */
    @Resource
    private SysUserService sysUserService;
    @Autowired
    private YmlConfig ymlConfig;
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private RedisUtils redisUtils;
    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiOperation(value = "查询用户通过id", notes = "参数：id")
    @GetMapping("/selectOne/{id}")
    public ResponseWrapper selectOne(@PathVariable("id") String id) {
        try{
            SysUser user=this.sysUserService.queryById(id);
            return user!=null ?ResponseWrapper.success(200, "查询成功", user):ResponseWrapper.error(500, "查询失败");
        }catch (Exception e){
            e.printStackTrace();
            log.error("活动分页查询失败{}", e.getMessage());
            return ResponseWrapper.error(500, "活动信息查询失败");
        }
    }

    /**
     * @projectName: SysUserMapper
     * @Description: 通过userName 进行查询
     * @author zxh
     * @date 2018/11/18 16:45
     */
    @ApiOperation(value = "查询用户通过Name", notes = "参数：userName")
    @GetMapping("/selectOneByName/{name}")
    public ResponseWrapper selectOneByName(@PathVariable("name") String name) {
        try{
            SysUser user=this.sysUserService.queryByName(name);
            return ResponseWrapper.success(200, "查询成功", user);
        }catch (Exception e){
            e.printStackTrace();
            log.error("活动分页查询失败{}", e.getMessage());
            return ResponseWrapper.error(500, "活动信息查询失败");
        }
    }

    /**
     * @projectName: SysUserMapper
     * @Description: 删除用户 通过id 假删除
     * @author zxh
     * @date 2018/11/18 16:45
     */
    @ApiOperation(value = "删除用户 通过id", notes = "参数：id")
    @GetMapping("/deleteUserById/{id}")
    public ResponseWrapper deleteUserById(@PathVariable("id") String id) {
        try{
            //假删除
            SysUser user=new SysUser();
            user.setId(id);
            user.setIsDeleted(1);
            return this.sysUserService.update(user)>0?ResponseWrapper.success("删除成功"):ResponseWrapper.error(500, "删除失败");
        }catch (Exception e){
            e.printStackTrace();
            log.error("活动分页查询失败{}", e.getMessage());
            return ResponseWrapper.error(500, "删除失败");
        }
    }
    @ApiOperation(value = "查询用户", notes = "参数：page user")
    @GetMapping("/index")
    public ResponseWrapper index(PageUtil page, SysUser user){
        try{
            System.out.printf(""+page.toString()+"--");
            PageInfo<List<SysUser>> list =sysUserService.queryAllByLimit(page.getPage(),page.getLimit(),user);
            if (ObjectUtils.notEqual(list, null)) {
                return ResponseWrapper.success(200, "查询成功", list);
            }
            return ResponseWrapper.error();
        }catch (Exception e){
            e.printStackTrace();
            log.error("活动分页查询失败{}", e.getMessage());
            return ResponseWrapper.error(500, "活动信息查询失败");
        }

    }
    @ApiOperation(value = "跟新或者新增用户", notes = "参数： user")
    @PostMapping("/updateOrInsertByUser")
    public ResponseWrapper updateOrInsert(@RequestBody SysUser user){
        try{
            //修改
            if(StringUtils.isNotEmpty(user.getId())){
                user.setUpdateTime(new Date());
                //user.setPassword(StringUtils.isNotEmpty(user.getPassword())? DigestUtils.md5Hex(user.getPassword()):null);
                return this.sysUserService.update(user)>0?ResponseWrapper.success("修改成功"):ResponseWrapper.error(500, "修改失败");
            }
            //增加
            else if(StringUtils.isEmpty(user.getId())){
                user.setCreateTime(new Date());
                user.setId(UUID.randomUUID().toString().replace("-",""));
                //默认密码
                user.setPassword( ymlConfig.getPassword());
                return this.sysUserService.insert(user)>0?ResponseWrapper.success("添加成功"):ResponseWrapper.error(500, "添加失败");
            }else{
                return ResponseWrapper.error(500, "操作失败");
            }

        }catch (Exception e){
            e.printStackTrace();
            log.error("修改失败{}", e.getMessage());
            return ResponseWrapper.error(500, "修改失败");
        }
    }

      /**
          * @projectName: SysUserController
          * @Description: 获取当前用户
          * @author zxh
          * @date 2018/11/19 21:01
          */
      @ApiOperation(value = "查询当前用户", notes = "参数： user")
      @PostMapping("/findUser")
    public SysUser findUser(){
        Cookie[] cookies = request.getCookies();
        String token="";
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("token")) {
                token = cookie.getValue();
                System.out.println(token);
            }
        }
        SysUserVo userVo= (SysUserVo)redisUtils.get(token);
        return userVo.getUser();
    }

}